package cn.lg.soar.system.biz.modules.monitor.controller;

import cn.lg.soar.common.model.HttpResult;
import cn.lg.soar.common.model.PageQuery;
import cn.lg.soar.common.model.PageResult;
import cn.lg.soar.common.util.AssertUtil;
import cn.lg.soar.core.annotations.constraints.Id;
import cn.lg.soar.database.query.QueryParams;
import cn.lg.soar.database.query.SqueryWapper;
import cn.lg.soar.mvc.annotations.DetailMapping;
import cn.lg.soar.mvc.annotations.QueryMapping;
import cn.lg.soar.mvc.annotations.RemoveMapping;
import cn.lg.soar.system.api.constant.ModuleConst;
import cn.lg.soar.system.biz.modules.auth.entity.User;
import cn.lg.soar.system.biz.modules.auth.service.IUserService;
import cn.lg.soar.system.biz.modules.monitor.entity.OperationLog;
import cn.lg.soar.system.biz.modules.monitor.model.OperationLogVO;
import cn.lg.soar.system.biz.modules.monitor.service.OperationLogService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author luguoxiang
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@Tag(name = "操作日志")
@RestController
@RequestMapping(ModuleConst.MODULE_NAME + "/log")
public class OperationLogController {

    @Value("${lg.monitor.log.retention-days:60}")
    private Integer day;

    @Autowired
    private OperationLogService service;
    @Autowired
    private IUserService userService;

    @RequestMapping(path = "query", method = RequestMethod.GET)
    public HttpResult<PageResult<OperationLogVO>> query(PageQuery pageQuery, QueryParams params){
        PageResult<OperationLog> result = new SqueryWapper<>(OperationLog.class).query(this.service, pageQuery, params);
        PageResult<OperationLogVO> convert = result.convert(OperationLogVO.class);
        List<OperationLogVO> vos = convert.getList().stream().map((x) -> {
            OperationLogVO vo = new OperationLogVO();
            BeanUtils.copyProperties(x, vo);
            return vo;
        }).collect(Collectors.toList());
        Map<Integer, List<OperationLogVO>> grouping = vos.stream().collect(Collectors.groupingBy(OperationLogVO::getUserType));
        List<OperationLogVO> list = grouping.get(0);
        if (list != null) {
            Set<Long> userIds = list.stream().map(OperationLogVO::getUserId).collect(Collectors.toSet());
            Map<?, String> userMap = userService.mapByIds(userIds, User::getNickname);
            for (OperationLogVO x : list) {
                x.setNickname(userMap.get(x.getUserId()));
            }
        }
        convert.setList(vos);
        return HttpResult.data(convert);
    }

    @RequestMapping(path = "remove", method = RequestMethod.POST)
    public HttpResult<Void> remove(@RequestBody List<Long> ids){
        LocalDateTime dateTime = LocalDateTime.now().minusDays(day);
        AssertUtil.isTrue(
                this.service.remove(
                        Wrappers.<OperationLog>lambdaUpdate()
                                .in(OperationLog::getId, ids)
                                .le(OperationLog::getStartTime, dateTime)
                )
                , "删除日志失败，只能删除超过{0}天的日志", day);
        return HttpResult.success();
    }

    @RequestMapping(path = "detail", method = RequestMethod.GET)
    public HttpResult<OperationLog> detail(@RequestParam(name = "id") @Id Long id) {
        return HttpResult.data(this.service.getById(id));
    }

}
